import datetime
import random
import re
from flask import current_app, jsonify
from flask import json
from flask import request
# from flask import session
from flask import session

from info import constants, db
from info import redis_store
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue

# 图片验证码
@passport_blue.route('/image_code')
def get_image_code():
    # 创建验证码
    _, text, img_data = captcha.generate_captcha()

    # 获取ｕｕｉｄ
    cur_id = request.args.get('cur_id')
    pre_id = request.args.get('pre_id')
    try:
        redis_store.set('uuid:%s' % cur_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
        # 判断rep_id是否存在，存在则删除
        if pre_id:
            # 存入redis
            redis_store.delete('uuid:%s' % pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="redis操作异常")
    # 返回验证码图片


    return img_data

# 手机验证码
@passport_blue.route('/sms_code', methods=['POST'])
def sms_code():
    # 思路分析:
    # 接收参数
    json_data = request.data
    dict_data = json.loads(json_data)

    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 校验参数, 为空校验
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    # 校验手机号格式是否正确
    if not re.match('1[345678]\\d{9}', mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号格式有误")
    # 通过验证码编号, 取出图片验证码A
    try:
        redis_image_code = redis_store.get('uuid:%s' % image_code_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="redis获取异常")

    # 判断验证码A
    if not redis_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码过期")

    # 判断图片验证码是否正确
    if image_code.upper() != redis_image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="图片填写错误")

    ren_code = "%06d" % random.randint(0, 999999)  # 生成6位数的随机短信验证码
    current_app.logger.error("短信验证码是 = %s" % ren_code)
    # # 调用CCP发送短信方法
    # try:
    #     ccp = CCP()
    #     ret_num = ccp.send_template_sms(mobile,[ren_code,constants.SMS_CODE_REDIS_EXPIRES/6],1)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.THIRDERR,errmsg="云通讯发送异常")
    # # 判断短信是否发送成功
    # if ret_num == -1:
    #     return jsonify(errno=RET.DATAERR,errmsg="短信发送失败")
    # # 保存短信到redis中
    try:
        redis_store.set("sms_code:%s" % mobile, ren_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="短信验证码保存异常")
    # 返回发送的状态
    return jsonify(errno=RET.OK, errmsg='没有问题，后台处理完毕')

# 点击注册
@passport_blue.route('/register', methods=['POST'])
def register():
    #     1.获取参数
    dict_data = request.json
    mobile = dict_data.get("mobile")
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")
    #     2.校验参数,为空校验
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    # 3.手机号格式校验
    if not re.match('1[345678]\\d{9}', mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号格式有误")
    # 4.根据手机号取出redis中的短信验证码
    try:
        redis_sms_code = redis_store.get('sms_code:%s' % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取短信验证码失败")
    # 5.判断短信验证码是否过期
    if not redis_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码已过期")

    # 6.校验短信验证码是否正确
    if redis_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码填写错误")

    # 7.创建用户对象
    #     8.设置用户对象的属性信息
    user = User()
    user.nick_name = mobile
    user.password = password
    user.mobile = mobile
    # print(user.password)
    # 9.保存用户到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="用户创建失败")

    # 10.返回响应信息
    return jsonify(errno=RET.OK, errmsg="注册成功")

# 点击登录
@passport_blue.route('/login', methods=['POST'])
def login():
    print('viewssssssssssssssssss')
    # 获取参数
    dict_data = request.json
    mobile = dict_data.get("mobile")
    password = dict_data.get("password")
    # 校验参数
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 根据手机号取出用户对象
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户失败")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="该用户不存在")
    # 判断密码正确性
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg="密码输入错误")

    # 将用户的登陆信息存到session
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile

    user.create_time = datetime.datetime.now()

    # try:
    #     db.session.commit()
    # except Exception as e:
    #     current_app.loger.error(e)

    # 返回响应
    return jsonify(errno=RET.OK, errmsg="登陆成功")

# 点击登出
@passport_blue.route('/logout')
def logout():
    print('aa')
    # 清除session信息
    session.pop("user_id", None)
    session.pop("nick_name", None)
    session.pop("mobile", None)

    return jsonify(errno=RET.OK, errmsg="退出成功")